package site.yunnong.atvris.common.utils;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;

/**
 * @author JinghaoZhang
 * @date 2021年-04月-30日
 */
public class FrameGrabberUtils {

    private static int DEFAULT_INTERCEPTION_FRAMES = 30;

    public static void getVideoCover(File videoFile, File coverFile, String imageType) throws IOException {

        FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videoFile);
        ff.start();

        int length = ff.getLengthInFrames();
        int i = 0;
        int interceptionFrame = DEFAULT_INTERCEPTION_FRAMES;
        if (interceptionFrame >= length * 0.8) {
            interceptionFrame = (int)(length * 0.3);
        }
        Frame frame = null;
        while (i < length) {
            // 过滤interceptionFrame之前的帧，避免出现全黑的帧
            frame = ff.grabFrame();
            if ((i > interceptionFrame) && (frame.image != null)) {
                break;
            }
            i++;
        }
        ImageIO.write(new Java2DFrameConverter().getBufferedImage(frame),
                imageType, coverFile);
        ff.stop();
    }

    public static long getVideoTime(File videoFile) throws IOException {
        FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videoFile);
        ff.start();
        long time = ff.getLengthInTime()/(1000 * 1000);
        ff.stop();
        return time;
    }

    /**
     * 支持远程文件解析长度
     * @param url
     * @return
     * @throws IOException
     */
    public static long getVideoTime(String url) throws IOException {
        FFmpegFrameGrabber ff = new FFmpegFrameGrabber(url);
        ff.start();
        long time = ff.getLengthInTime()/(1000 * 1000);
        ff.stop();
        return time;
    }

    public static void main(String[] args) throws IOException{
        FFmpegFrameGrabber ff = new FFmpegFrameGrabber("https://replay.video.191.cn/video/191shipin/2021shipin/202103/wyz1-0323.mp4");
        ff.start();
        long time = ff.getLengthInTime();
        System.out.println(time);
//        System.out.println(ff.);
        ff.stop();
    }
}
